package com.dongdongshop.mq;

import com.dongdongshop.mapper.TbSeckillGoodsMapper;
import com.dongdongshop.mapper.TbSeckillOrderMapper;
import com.dongdongshop.pojo.TbSeckillGoods;
import com.dongdongshop.pojo.TbSeckillOrder;
import com.dongdongshop.service.SeckillService;
import com.dongdongshop.util.IdWorker;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.Map;
@Component
@RocketMQMessageListener(topic = "yangyangyang",consumerGroup = "tttt")
public class SeckillMqConsumer implements RocketMQListener<Map>{
    @Autowired
    private TbSeckillGoodsMapper tbSeckillGoodsMapper;
    @Autowired
    private TbSeckillOrderMapper tbSeckillOrderMapper;
    @Autowired
    private RedisTemplate redisTemplate;
    @Override
    public void onMessage(Map map) {
        IdWorker idWorker = new IdWorker();
        String  username = (String) map.get("username");
        Long id = Long.parseLong(map.get("id").toString());
        long orderId = idWorker.nextId();
        try {

            TbSeckillGoods goods = tbSeckillGoodsMapper.selectByPrimaryKey(id);
            //4.创建订单
            TbSeckillOrder order = new TbSeckillOrder();
            order.setId(orderId);
//        order.setUserId(username);
            order.setStatus("1");//待支付
            order.setSellerId(goods.getSellerId());
            order.setSeckillId(goods.getId());
            order.setMoney(goods.getCostPrice());
            order.setCreateTime(new Date());
            tbSeckillOrderMapper.insertSelective(order);
            System.out.println("订单保存成功");
            redisTemplate.boundHashOps("order1").put(username,orderId);
        }catch (Exception e){
            System.out.println("订单保存失败");
            redisTemplate.boundHashOps("order1").put(username,-1L);
        }

    }
}
